﻿using System;
using System.Collections.Generic;

namespace WindowsPhone.CompactContainer.Aggregator
{
    /// <remarks />
    public class EventPublisher : IEventPublisher
    {
        /// <remarks />
        public EventPublisher()
        {
            EventHandlers = new EventHandlers();
        }

        /// <remarks />
        public void OnHandlerError(Action<Exception> errorHandler)
        {
            EventHandlers.OnHandlerError(errorHandler);
        }

        /// <remarks />
        public void Publish<T>(T eventData)
        {
            EventHandlers.Handle(eventData);
        }

        /// <remarks />
        public EventHandlerOptions RegisterHandler<T>(IEventHandler<T> eventHandler)
        {
            var handler = new EventHandlerOptions(eventHandler);
            EventHandlers.Add<T>(handler);
            return handler;
        }

        /// <remarks />
        public IList<EventHandlerOptions> RegisterHandlers(object eventHandler)
        {
            var list = new List<EventHandlerOptions>();
            var interfaces = eventHandler.GetType().GetInterfaces();
            var type = typeof(IEventHandler<>);
            foreach (var type2 in interfaces)
            {
                if (type2.Name.Equals(type.Name))
                {
                    var eventType = type2.GetGenericArguments()[0];
                    var handler = new EventHandlerOptions(eventHandler);
                    EventHandlers.Add(eventType, handler);
                    list.Add(handler);
                }
            }
            return list;
        }

        /// <remarks />
        public void UnregisterHandler(object eventHandler)
        {
            EventHandlers.Remove(eventHandler);
        }

        private readonly EventHandlers EventHandlers;
    }
}
